﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace AnaViewer
{
    /// <summary>
    /// 设置窗体的可拖动样式。
    /// </summary>
    public class FormDrag
    {
        Control ctrl;
        public FormDrag(Control ctrl)
        {
            this.ctrl = ctrl;
            ctrl.MouseDown += new MouseEventHandler(Ctrl_MouseDown);
            ctrl.MouseMove += new MouseEventHandler(Ctrl_MouseMove);
            ctrl.MouseUp += new MouseEventHandler(Ctrl_MouseUp);
        }
        /// <summary>
        /// 设置一个控件为可拖动。
        /// </summary>
        /// <param name="ctrl"></param>
        public static void SetControlDragEnable(Control ctrl)
        {
            FormDrag drag = new FormDrag(ctrl);
        }

        //// Let Windows drag this form for us
        //protected override void WndProc(ref Message m)
        //{
        //    if (m.Msg == 0x0084 /*WM_NCHITTEST*/)
        //    {
        //        m.Result = (IntPtr)2;	// HTCLIENT
        //        return;
        //    }
        //    base.WndProc(ref m);
        //}

        /// <summary>
        /// Gets or sets 一个值，指示是否 [form locked]。
        /// </summary>
        /// <value>如果 [form locked]为 <c>true</c>；否则为 <c>false</c>。</value>
        public bool FormLocked
        {
            get { return m_FormLocked; }
            set { m_FormLocked = value; }
        }


        /// <summary>
        /// 如果锁定,则不移动
        /// </summary>
        private bool m_FormLocked = false;
        /// <summary>
        /// 记录鼠标指针的坐标
        /// </summary>
        private Point mouseOffset;
        /// <summary>
        /// 记录鼠标按键是否按下。修改鼠标状态 isMouseDown 的值
        /// </summary>
        private bool isMouseDown = false;
        public void Ctrl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {// 确保只有鼠标左键按下并移动时，才移动窗体
                mouseOffset = e.Location;
                ctrl.Cursor = Cursors.Hand;
                isMouseDown = true;
            }
        }
        public void Ctrl_MouseMove(object sender, MouseEventArgs e)
        {
            if (!m_FormLocked && isMouseDown)
            {
                Point pos = ctrl.Location;
                pos.Offset(e.X - mouseOffset.X,e.Y - mouseOffset.Y);
                ctrl.Location = pos;
            }
        }
        public void Ctrl_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = false;
                ctrl.Cursor = Cursors.Default;
            }
        }
    }
}
